package com.tjmc.tiomsresource.collect;

import com.tjmc.tiomsresource.service.*;
import com.tjmc.tiomsresource.thread.TranPtnHwPreThread;
import com.tjmc.tiomsresource.utils.CommonUtils;
import com.tjmc.tiomsresource.utils.SFTPUtils;
import com.tjmc.tiomsresource.utils.UnZipUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author Luc
 * @version 1.0
 * @date 2020-05-20 10:38
 * @description 从Corba 2.0接口, 采集、解析原始文件，并入库
 */
@Service
@PropertySource({"classpath:nce.properties"})
public class OmcResFetchJob {

    private static Logger logger = LoggerFactory.getLogger(OmcResFetchJob.class);

    @Value("${sftp.nce.host}")
    private String host;//服务器连接ip
    @Value("${sftp.nce.username}")
    private String username;//用户名
    @Value("${sftp.nce.password}")
    private String password;//密码
    @Value("${sftp.nce.port:22}")
    private int port;//端口号
    @Value("${sftp.nce.path.prefix}")
    private String sftpPathPrefix;
    @Value("${sftp.omc.local.path}")
    private String sftpLocalPath;
    @Value("${omc.parse.sync}")
    private int parseSync;

    @Autowired
    private TranPtnHwPreThread tranPtnHwPreThread;

    private SFTPUtils sftpUtils;
    @Autowired
    private UnZipUtils unZipUtils;

    @Autowired
    private CMCrdService cmCrdService;
    @Autowired
    private CMEqhService cmEqhService;
    @Autowired
    private CMEsiService cmEsiService;
    @Autowired
    private CMEspService cmEspService;
    @Autowired
    private CMEthService cmEthService;
    @Autowired
    private CMLbsService cmLbsService;
    @Autowired
    private CMMtrService cmMtrService;
    @Autowired
    private CMNelService cmNelService;
    @Autowired
    private CMPrtService cmPrtService;
    @Autowired
    private CMPswService cmPswService;
    @Autowired
    private CMPwtService cmPwtService;
    @Autowired
    private CMTdmService cmTdmService;
    @Autowired
    private CMTnlService cmTnlService;
    @Autowired
    private CMTpbService cmTpbService;
    @Autowired
    private CMTpiService cmTpiService;
    @Autowired
    private CMTplService cmTplService;
    @Autowired
    private CMSbnService cmSbnService;
    @Autowired
    private CMSnnService cmSnnService;

    @PostConstruct
    public void init() {
        logger.info("OmcResFetchJob(): " + host + ", " + port + ", " + username + ", " + password);
        this.sftpUtils = new SFTPUtils(host, port, username, password);
    }

    /*
     * @description:  下载一天全量的.xml.zip文件，1点下载包括0点生成的
     * @param:
     * @return:
     * @date: 2020/5/22
     */
    public boolean fetchCMData(String dayString) {
        sftpUtils.connect();
        String remotePath = sftpPathPrefix + "CM/" + dayString + "/";
        String localPath = sftpLocalPath + "CM/download/" + dayString + "/";
        logger.info("remotePath: " + remotePath);
        logger.info("localPath: " + localPath);
        File file = new File(localPath);
        if(!file.exists()) {
            file.mkdirs();
        }
        sftpUtils.batchDownLoadFile(remotePath, localPath, "CM-SPN-", ".xml.zip", false);
        sftpUtils.disconnect();
        return true;
    }

    /*
     * @description: 删除 parent 文件夹中，endline之前的所有 目录
     * @param: [parent, endline]
     * @return: boolean
     * @date: 2020/5/23
     */
    public void clearCMDataDir(Date endline) {
        File downloadDir = new File(sftpLocalPath + "CM/download/");
        File publicDir = new File(sftpLocalPath + "CM/public/");
        try {
            if(!downloadDir.exists() || !downloadDir.isDirectory()) {
                return;
            }
            for(File file : downloadDir.listFiles()) {
                Date fileDay = CommonUtils.string2utilDate(file.getName(), "yyyyMMdd");
                //endline: 20200523 fileDay: 20200520
                if(endline.getTime()-fileDay.getTime() >= 180*24*3600000) {
                    CommonUtils.deleleFile(file);
                }
            }
            if(!publicDir.exists() || !publicDir.isDirectory()) {
                return;
            }
            for(File file : publicDir.listFiles()) {
                Date fileDay = CommonUtils.string2utilDate(file.getName(), "yyyyMMdd");
                //endline: 20200523 fileDay: 20200520
                if(endline.getTime()-fileDay.getTime() >= 180*24*3600000) {
                    CommonUtils.deleleFile(file);
                }
            }
        } catch (ParseException e) {
            logger.info("格式化日期错误: " + endline);
        }
    }

    /*
     * @description:  解压缩最新的一次资源文件，lastTime 在 [0-12] 解压缩 0点采集文件；在 [12-24] 解压缩 12点采集文件
     * @param: [dayString, lastTime]
     * @return: java.util.List<java.io.File>
     * @date: 2020/5/22
     */
    public List<File> unZipCMData(String dayString, Date lastTime) {
        String localPath = sftpLocalPath + "CM/download/" + dayString + "/";
        String unZipPath = sftpLocalPath + "CM/public/" + dayString + "/";
        File rootPath = new File(localPath);
        if(!rootPath.exists()) {
            logger.info("解压缩源目录不存在：" + localPath);
            return null;
        }
        if(rootPath.listFiles().length == 0) {
            logger.info("解压缩文件个数为0");
            return null;
        }
        File file = new File(unZipPath);
        CommonUtils.deleleFile(file);
        if(!file.exists()) {
            file.mkdirs();
        }
        List<File> unZipFiles = new ArrayList<>();
        for(File localFile : rootPath.listFiles()) {
            String[] fileNames = localFile.getName().split("-");
            if(null == fileNames || fileNames.length < 6) {
                logger.info("解压缩源文件名错误：" + localFile.getName());
                continue;
            }
            if(fileNames[5].endsWith(".xml")) {
                fileNames[5] = fileNames[5].substring(0, fileNames[5].indexOf(".xml.zip"));
            }
            logger.info("解压缩源文件日期：" + fileNames[5]);
            try {
                Date fileDate = CommonUtils.string2utilDate(fileNames[5], "yyyyMMddHHmmss");
                /*
                 TODO: 临时注掉，在 [12-24] 解压缩 12点采集文件，不采集0点生成的文件
                 */
                if(!fileDate.after(new Date(lastTime.getTime()-12*60*60*1000))) {
                    continue;
                }
                unZipFiles.addAll(unZipUtils.unZip(localFile, unZipPath));
            } catch (Exception e) {
                logger.info("解压缩源文件错误：" + localFile.getAbsolutePath());
                continue;
            }
        }
        return unZipFiles;
    }

    public boolean saveTranPtnHwDataToDB(List<File> xmlFiles) {
        if(parseSync == 0) {
            if(!cmCrdService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmEqhService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmEsiService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmEspService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmEthService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmLbsService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmMtrService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }

            if(!cmNelService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmPrtService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmPswService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmPwtService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmTdmService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmTnlService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmTpbService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmTpiService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmTplService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmSbnService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
            if(!cmSnnService.saveTranPtnHwDataToDB(xmlFiles)) {
                return false;
            }
        } else if(parseSync == 1) {
            CompletableFuture<Boolean> result1 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmCrdService, xmlFiles);
            CompletableFuture<Boolean> result2 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmEqhService, xmlFiles);
            CompletableFuture<Boolean> result3 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmEsiService, xmlFiles);
            CompletableFuture<Boolean> result4 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmEspService, xmlFiles);
            CompletableFuture<Boolean> result5 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmEthService, xmlFiles);
            CompletableFuture<Boolean> result6 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmLbsService, xmlFiles);
            CompletableFuture<Boolean> result7 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmMtrService, xmlFiles);
            CompletableFuture<Boolean> result8 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmNelService, xmlFiles);
            CompletableFuture<Boolean> result9 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmPrtService, xmlFiles);
            CompletableFuture<Boolean> result10 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmPswService, xmlFiles);
            CompletableFuture<Boolean> result11 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmTdmService, xmlFiles);
            CompletableFuture<Boolean> result12 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmTnlService, xmlFiles);
            CompletableFuture<Boolean> result13 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmTpbService, xmlFiles);
            CompletableFuture<Boolean> result14 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmTpiService, xmlFiles);
            CompletableFuture<Boolean> result15 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmTplService, xmlFiles);
            CompletableFuture<Boolean> result16 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmPwtService, xmlFiles);
            CompletableFuture<Boolean> result17 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmSbnService, xmlFiles);
            CompletableFuture<Boolean> result18 = tranPtnHwPreThread.saveTranPtnHwDataToDB(cmSnnService, xmlFiles);

            CompletableFuture.allOf(result1, result2, result3, result4, result5, result6, result7, result8, result9,
                    result10, result11, result12, result13, result14, result15, result16, result17, result18).join();
        }
        return true;
    }
}
